package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 定义 people结构体类型
type people struct {
	ID          string `json:id`
	NAME        string `json:name`
	AGE         int    `json:age`
	DESCRIPTION string `json:description`
}

// 初始化数据
var peoples = []people{
	{ID: "1", NAME: "John", AGE: 20, DESCRIPTION: "This is John"},
	{ID: "2", NAME: "Jane", AGE: 21, DESCRIPTION: "This is Jane"},
	{ID: "3", NAME: "Jim", AGE: 22, DESCRIPTION: "This is Jim"},
}

func getAll(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, peoples)
}

func getOne(c *gin.Context) {
	id := c.Param("id")
	for _, p := range peoples {
		if p.ID == id {
			c.IndentedJSON(http.StatusOK, p)
			return
		}
	}
	c.IndentedJSON(http.StatusNotFound, gin.H{"error": "not found"})
}

func addOne(c *gin.Context) {
	var newPeople people
	if err := c.BindJSON(&newPeople); err != nil {
		return
	}
	peoples = append(peoples, newPeople)
	c.IndentedJSON(http.StatusCreated, newPeople)
}

func delOne(c *gin.Context) {
	id := c.Param("id")
	for i, p := range peoples {
		if p.ID == id {
			peoples = append(peoples[:i], peoples[i+1:]...)
			c.IndentedJSON(http.StatusOK, gin.H{"status": "ok"})
			return
		}
	}
	c.IndentedJSON(http.StatusNotFound, gin.H{"error": "not found"})

}

func main() {
	router := gin.Default()
	router.GET("/getAll", getAll)
	router.GET("/getOne/:id", getOne)
	router.POST("/addOne", addOne)
	router.DELETE("/delOne/:id", delOne)

	router.Run("localhost:8000")
}
